package com.hd.manager.interceptor;

import com.hd.manager.shiro.ShiroUtils;
import com.hd.manager.shiro.token.TokenManager;
import com.hd.hdxgddcommon.entity.dto.ResultDto;
import com.hd.hdxgddcommon.utils.JwtUtil;
import com.hd.hdxgddcommon.utils.StringUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
//第一步：自定义拦截器
//实现HandlerInterceptor这个接口
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String authorization = request.getHeader("token");
            if (StringUtils.isNotBlank(authorization)) {
                String token = authorization;
                Claims claims = JwtUtil.parseJWT(token, JwtUtil.KEY);
                Date expiration = claims.getExpiration();
                if (System.currentTimeMillis() > expiration.getTime()) {
                    s401("token已失效!",response);
                    return false;
                }
                TokenManager.claimsThreadLocal.set(claims);
                return true;
            }
            s401("token为空!",response);
            return false;
        } catch (Exception e) {
            s401(e.getMessage(), response);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TokenManager.claimsThreadLocal.remove();
    }

    private void s401(String message, HttpServletResponse response) {
        response.setStatus(401);
        ShiroUtils.responseJson(response, new ResultDto(0, message));
    }
}
